package com.tools.scanner.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.core.net.toUri
import com.google.android.play.core.review.ReviewException
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManagerFactory
import com.tools.scanner.QrApp
import com.tools.scanner.R
import com.tools.scanner.bean.SharePlatformInfo
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class AppUtil {

    companion object {

        fun getPackageName(): String {
            return QrApp.app.packageName
        }

        fun rateUs(activity: Activity) {
            val currentDate = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date())
            val key = "rate_$currentDate"

            if (PreferencesUtil.getBooleanValue(key, false)) {
                return
            }
            PreferencesUtil.putValue(key, true)

            val manager = ReviewManagerFactory.create(activity)
            val request = manager.requestReviewFlow()
            request.addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    val reviewInfo = task.result
                    manager.launchReviewFlow(activity, reviewInfo)
                    DataReportUtil.reportRateUsOpen()
                } else {
                    val exception = task.exception as? ReviewException
                    if (exception != null) {
                        val reviewErrorCode = exception.errorCode
                        DataReportUtil.reportRateUsOpenFail(reviewErrorCode, exception.toString())
                    }
                }
            }
        }

        fun sendFeedback() {
            val context = QrApp.app
            val appName = context.resources.getString(R.string.app_name)
            val versionName = getVersionName()
            val mailto =
                "mailto:szxiaolansong@gmail.com?subject=【Feedback】${appName} – v${versionName}"

            val intent = Intent(Intent.ACTION_SENDTO).apply {
                data = mailto.toUri()
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            try {
                context.startActivity(intent)
            } catch (e: ActivityNotFoundException) {
                e.printStackTrace()
            }
        }

        fun getVersionCode(): Int {
            val context = QrApp.app
            return context.packageManager.getPackageInfo(context.packageName, 0).versionCode
        }

        fun getVersionName(): String {
            val context = QrApp.app
            return context.packageManager.getPackageInfo(context.packageName, 0).versionName
        }

        fun getOSLang(): String {
            return getLocale().language
        }

        fun getOSCountry(): String {
            return getLocale().country
        }

        fun getLocale(): Locale {
            val context = QrApp.app
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                context.resources.configuration.locales.get(0)
            } else {
                context.resources.configuration.locale
            }
        }

        fun openGpLink() {
            val context = QrApp.app
            val url = "https://play.google.com/store/apps/details?id=${context.packageName}"

            try {
                val intent = Intent(Intent.ACTION_VIEW)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.setClassName(
                    "com.android.vending",
                    "com.google.android.finsky.activities.MainActivity"
                )
                intent.data = url.toUri()
                context.startActivity(intent)
                return
            } catch (e: Exception) {
                e.printStackTrace()
            }

            try {
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data = url.toUri()
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                context.startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun shareApp(info: SharePlatformInfo) {
            val context = QrApp.app

            val intent = Intent("android.intent.action.SEND")
            intent.setType("text/plain")
            intent.setPackage(info.packageName)
            intent.putExtra("android.intent.extra.TITLE", "str2")
            intent.putExtra("android.intent.extra.TEXT", "str3")
            intent.putExtra("skip_preview", true)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            try {
                context.startActivity(intent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun isInMainProcess(): Boolean {
            val context = QrApp.app

            val pid = android.os.Process.myPid()
            val activityManager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

            val list = activityManager.runningAppProcesses
            if (list != null) {
                for (item in list) {
                    if (item.pid == pid && item.processName.equals(context.packageName)) {
                        return true
                    }
                }
            }

            return false
        }
    }
}